package com.tiezhu.springdemo.mqtt;

import com.tiezhu.springdemo.bean.FeedHistory;
import com.tiezhu.springdemo.mapper.HistoryMapper;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

public class MqttClientCallback implements MqttCallback {


    @Override
    public void connectionLost(Throwable arg0) {
        System.out.println("mqtt 失去了连接");
        MqttClientUtil.subscribeReconnect();
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken arg0) {
        System.out.println("mqtt 发送完成！");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message)
            throws Exception {
        String content = new String(message.getPayload(), "utf-8");
//        if (topic.equals("test1")){
////            animal(content);
//        }
//        if (topic.equals("device/admin/feed"))
//        {
//            System.out.println(content);
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//            System.out.println(String.valueOf(df.format(new Date())));// new Date()为获取当前系统时间
//            FeedHistory feedHistory = new FeedHistory("1",df.format(new Date()),"admin");
//            int i = historyMapper.addHistory(feedHistory);
//            System.out.println(i);
//            if (i == 1){
//                MqttClientUtil.publish_common("test2","猫咪来吃猫粮啦");
//            }
//        }
        System.out.println("收到mqtt消息,topic: " + topic + " ,content: " + content);
        if (MqttClientUtil.executorService != null){
            MqttClientUtil.executorService.execute(new HanderThread(topic,content));
        }
    }


}